/*
  学习目标：实现评论列表
  需求： 借助生命周期的更新阶段-模拟watch监听数据
*/

import React from 'react';
import CommentList from './components/CommentList';
import Header from './components/Header';
import './index.css';
export default class App extends React.Component {
  handleDel = (id) => {
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    });
  };

  handleClear = () => {
    this.setState({ list: [] });
  };

  handleAdd = (obj) => {
    this.setState({
      list: [obj, ...this.state.list],
    });
  };

  componentDidUpdate() {
    // 做前端缓存
    localStorage.setItem('comment-list', JSON.stringify(this.state.list));
    localStorage.setItem('showOwner', JSON.stringify(this.state.showOwner));
  }

  state = {
    //  1. 声明一个状态控制只看思聪 showOwner : false
    showOwner: JSON.parse(localStorage.getItem('showOwner')) || false,
    list: JSON.parse(localStorage.getItem('comment-list')) || [],
  };

  /* 通过function封装计算函数 */
  showListByOwner = () => {
    const { list, showOwner } = this.state;
    return list.filter((item) => (showOwner ? item.username === '思聪' : true));
  };
  render() {
    return (
      <div className="app">
        <Header handleClear={this.handleClear} handleAdd={this.handleAdd}></Header>
        {/*  // 2. 点击时 修改showOwner 为true */}
        <button onClick={() => this.setState({ showOwner: !this.state.showOwner })}>
          只看楼主
        </button>
        {/* 4. 将showList传给CommentList的list属性 */}
        {/* 3. 🔑 通过render函数会被setState触发，声明变量，模拟一个计算属性 */}
        <CommentList list={this.showListByOwner()} handleDel={this.handleDel}></CommentList>
      </div>
    );
  }
}
